
package com.choosefine.base.shixiaobao.base;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.choosefine.base.shixiaobao.common.def.ResultCode;
import com.choosefine.base.shixiaobao.common.exception.RespExcption;
import com.choosefine.base.shixiaobao.common.json.JsonResult;
import com.choosefine.base.shixiaobao.common.json.JsonUtil;

/**
 * 过滤web请求
 * 
 * @author Yichen.Qi
 * @data 2016年9月17日
 * @desc WebControllerAspect.java
 */
@Component
@Aspect
public class WebControllerAspect
{

	private static final Logger logger = LoggerFactory.getLogger(WebControllerAspect.class);

	// 拦截web请求
	// update code liaozhanggen 2017-01-10 过虑任意Controller类的异常
	@Around("execution(* com.choosefine.base.shixiaobao.*.controller.*Controller.*(..))")
	public Object doControllerAround(ProceedingJoinPoint pjp) throws Throwable {
		JsonResult<Object> jsonResult = null;
		Object result = null;
		// 是否返回json
		try
		{
//			// 统一对bindresult进行校验      delete code liaozhanggen 2017-05-05 ,引发部分接口 java.lang.NullPointerException
//        	Object[] args = pjp.getArgs();
//        	for (Object arg:args) {
//        		if (!arg.getClass().equals(BeanPropertyBindingResult.class)) {
//        			continue;
//        		}
//        		BindingResult bindingResult = (BindingResult) arg;
//    			if (bindingResult.hasErrors()) {
//    				JsonResult<Object> r = new JsonResult<>(null, bindingResult.getAllErrors().get(0).getDefaultMessage(), ResultCode.FAILED);
//    				return r.toJson();
//    			}
//        	}
            result = pjp.proceed();
		} catch (RespExcption e)
		{
			// 断言时抛出的错误
			jsonResult = new JsonResult<>(null, e.getMessage(), e.getCode());
			result = JsonUtil.toJson(jsonResult);
		} catch (Exception e)
		{
			e.printStackTrace();
			// 程序内部错误, 交给 Whitelabel Error Page 处理
			logger.error(e.getMessage());
			// add code by liaozhanggen 2017-03-24 统一返回结果
			jsonResult = new JsonResult("请求方式或参数不符合", e.getMessage(),ResultCode.SERVERERROR_INTERNAL);
			result = JsonUtil.toJson(jsonResult);
//						throw e;
		}
		return result;
	}

}
